/*
 * Copyright 2012-2022 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.autoconfigure.amqp;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.AddressShuffleMode;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory.CacheMode;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory.ConfirmType;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.convert.DurationUnit;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * Rabbit 的配置属性。
 *
 * @author Greg Turnquist
 * @author Dave Syer
 * @author Stephane Nicoll
 * @author Andy Wilkinson
 * @author Josh Thornhill
 * @author Gary Russell
 * @author Artsiom Yudovin
 * @author Franjo Zilic
 * @author Eddú Meléndez
 * @since 1.0.0
 */
@ConfigurationProperties(prefix = "spring.rabbitmq")
public class RabbitProperties {

	private static final int DEFAULT_PORT = 5672;

	private static final int DEFAULT_PORT_SECURE = 5671;

	private static final int DEFAULT_STREAM_PORT = 5552;

	/**
	 * RabbitMQ 主机地址。如果设置了 addresses，则忽略此配置。
	 */
	private String host = "localhost";

	/**
	 * RabbitMQ 端口号。如果设置了 addresses，则忽略此配置。默认端口为 5672，启用 SSL 时为 5671。
	 */
	private Integer port;

	/**
	 * 用于认证代理的登录用户名。
	 */
	private String username = "guest";

	/**
	 * 用于认证代理的登录密码。
	 */
	private String password = "guest";

	/**
	 * SSL 配置。
	 */
	private final Ssl ssl = new Ssl();

	/**
	 * 连接代理时使用的虚拟主机。
	 */
	private String virtualHost;

	/**
	 * 客户端应连接的地址列表，逗号分隔。设置后 host 和 port 将被忽略。
	 */
	private String addresses;

	/**
	 * 用于打乱配置地址的模式。
	 */
	private AddressShuffleMode addressShuffleMode = AddressShuffleMode.NONE;

	/**
	 * 请求的心跳超时时间；为零表示不启用。如果未指定时间单位，则默认使用秒。
	 */
	@DurationUnit(ChronoUnit.SECONDS)
	private Duration requestedHeartbeat;

	/**
	 * 客户端请求的每个连接的最大通道数。使用 0 表示无限制。
	 */
	private int requestedChannelMax = 2047;

	/**
	 * 是否启用发布者返回。
	 */
	private boolean publisherReturns;

	/**
	 * 使用的发布者确认类型。
	 */
	private ConfirmType publisherConfirmType;

	/**
	 * 连接超时时间。设置为零表示永远等待。
	 */
	private Duration connectionTimeout;

	/**
	 * 通道中 RPC 调用的持续时间超时。设置为零表示永远等待。
	 */
	private Duration channelRpcTimeout = Duration.ofMinutes(10);

	/**
	 * 缓存配置。
	 */
	private final Cache cache = new Cache();

	/**
	 * 监听器容器配置。
	 */
	private final Listener listener = new Listener();

	private final Template template = new Template();

	private final Stream stream = new Stream();

	private List<Address> parsedAddresses;

	public String getHost() {
		return this.host;
	}

	/**
	 * 返回第一个地址的主机，如果未设置地址则返回配置的主机。
	 * @return 主机地址
	 * @see #setAddresses(String)
	 * @see #getHost()
	 */
	public String determineHost() {
		if (CollectionUtils.isEmpty(this.parsedAddresses)) {
			return getHost();
		}
		return this.parsedAddresses.get(0).host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public Integer getPort() {
		return this.port;
	}

	/**
	 * 返回第一个地址的端口，如果未设置地址则返回配置的端口。
	 * @return 端口号
	 * @see #setAddresses(String)
	 * @see #getPort()
	 */
	public int determinePort() {
		if (CollectionUtils.isEmpty(this.parsedAddresses)) {
			Integer port = getPort();
			if (port != null) {
				return port;
			}
			return (Optional.ofNullable(getSsl().getEnabled()).orElse(false)) ? DEFAULT_PORT_SECURE : DEFAULT_PORT;
		}
		return this.parsedAddresses.get(0).port;
	}

	public void setPort(Integer port) {
		this.port = port;
	}

	public String getAddresses() {
		return this.addresses;
	}

	/**
	 * 返回逗号分隔的地址列表，或者如果未设置地址，则返回由配置的主机和端口组成的单一地址（{@code host:port}）。
	 * @return 地址字符串
	 */
	public String determineAddresses() {
		if (CollectionUtils.isEmpty(this.parsedAddresses)) {
			return this.host + ":" + determinePort();
		}
		List<String> addressStrings = new ArrayList<>();
		for (Address parsedAddress : this.parsedAddresses) {
			addressStrings.add(parsedAddress.host + ":" + parsedAddress.port);
		}
		return StringUtils.collectionToCommaDelimitedString(addressStrings);
	}

	public void setAddresses(String addresses) {
		this.addresses = addresses;
		this.parsedAddresses = parseAddresses(addresses);
	}

	private List<Address> parseAddresses(String addresses) {
		List<Address> parsedAddresses = new ArrayList<>();
		for (String address : StringUtils.commaDelimitedListToStringArray(addresses)) {
			parsedAddresses.add(new Address(address, Optional.ofNullable(getSsl().getEnabled()).orElse(false)));
		}
		return parsedAddresses;
	}

	public String getUsername() {
		return this.username;
	}

	/**
	 * 如果已设置地址且第一个地址有用户名，则返回该用户名。
	 * 否则返回调用 {@code getUsername()} 的结果。
	 * @return 用户名
	 * @see #setAddresses(String)
	 * @see #getUsername()
	 */
	public String determineUsername() {
		if (CollectionUtils.isEmpty(this.parsedAddresses)) {
			return this.username;
		}
		Address address = this.parsedAddresses.get(0);
		return (address.username != null) ? address.username : this.username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return this.password;
	}

	/**
	 * 如果已设置地址且第一个地址有密码，则返回该密码。
	 * 否则返回调用 {@code getPassword()} 的结果。
	 * @return 密码或 {@code null}
	 * @see #setAddresses(String)
	 * @see #getPassword()
	 */
	public String determinePassword() {
		if (CollectionUtils.isEmpty(this.parsedAddresses)) {
			return getPassword();
		}
		Address address = this.parsedAddresses.get(0);
		return (address.password != null) ? address.password : getPassword();
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Ssl getSsl() {
		return this.ssl;
	}

	public String getVirtualHost() {
		return this.virtualHost;
	}

	/**
	 * 如果已设置地址且第一个地址有虚拟主机，则返回该虚拟主机。
	 * 否则返回调用 {@code getVirtualHost()} 的结果。
	 * @return 虚拟主机或 {@code null}
	 * @see #setAddresses(String)
	 * @see #getVirtualHost()
	 */
	public String determineVirtualHost() {
		if (CollectionUtils.isEmpty(this.parsedAddresses)) {
			return getVirtualHost();
		}
		Address address = this.parsedAddresses.get(0);
		return (address.virtualHost != null) ? address.virtualHost : getVirtualHost();
	}

	public void setVirtualHost(String virtualHost) {
		this.virtualHost = StringUtils.hasText(virtualHost) ? virtualHost : "/";
	}

	public AddressShuffleMode getAddressShuffleMode() {
		return this.addressShuffleMode;
	}

	public void setAddressShuffleMode(AddressShuffleMode addressShuffleMode) {
		this.addressShuffleMode = addressShuffleMode;
	}

	public Duration getRequestedHeartbeat() {
		return this.requestedHeartbeat;
	}

	public void setRequestedHeartbeat(Duration requestedHeartbeat) {
		this.requestedHeartbeat = requestedHeartbeat;
	}

	public int getRequestedChannelMax() {
		return this.requestedChannelMax;
	}

	public void setRequestedChannelMax(int requestedChannelMax) {
		this.requestedChannelMax = requestedChannelMax;
	}

	public boolean isPublisherReturns() {
		return this.publisherReturns;
	}

	public void setPublisherReturns(boolean publisherReturns) {
		this.publisherReturns = publisherReturns;
	}

	public Duration getConnectionTimeout() {
		return this.connectionTimeout;
	}

	public void setPublisherConfirmType(ConfirmType publisherConfirmType) {
		this.publisherConfirmType = publisherConfirmType;
	}

	public ConfirmType getPublisherConfirmType() {
		return this.publisherConfirmType;
	}

	public void setConnectionTimeout(Duration connectionTimeout) {
		this.connectionTimeout = connectionTimeout;
	}

	public Duration getChannelRpcTimeout() {
		return this.channelRpcTimeout;
	}

	public void setChannelRpcTimeout(Duration channelRpcTimeout) {
		this.channelRpcTimeout = channelRpcTimeout;
	}

	public Cache getCache() {
		return this.cache;
	}

	public Listener getListener() {
		return this.listener;
	}

	public Template getTemplate() {
		return this.template;
	}

	public Stream getStream() {
		return this.stream;
	}

	public class Ssl {

		private static final String SUN_X509 = "SunX509";

		/**
		 * 是否启用 SSL 支持。如果地址中带有协议（amqp:// vs. amqps://）则自动判断。
		 */
		private Boolean enabled;

		/**
		 * 存放 SSL 证书的密钥库路径。
		 */
		private String keyStore;

		/**
		 * 密钥库类型。
		 */
		private String keyStoreType = "PKCS12";

		/**
		 * 访问密钥库的密码。
		 */
		private String keyStorePassword;

		/**
		 * 密钥库算法。
		 */
		private String keyStoreAlgorithm = SUN_X509;

		/**
		 * 存放 SSL 证书的信任库。
		 */
		private String trustStore;

		/**
		 * 信任库类型。
		 */
		private String trustStoreType = "JKS";

		/**
		 * 访问信任库的密码。
		 */
		private String trustStorePassword;

		/**
		 * 信任库算法。
		 */
		private String trustStoreAlgorithm = SUN_X509;

		/**
		 * 使用的 SSL 算法。默认由 Rabbit 客户端库配置。
		 */
		private String algorithm;

		/**
		 * 是否启用服务器端证书验证。
		 */
		private boolean validateServerCertificate = true;

		/**
		 * 是否启用主机名验证。
		 */
		private boolean verifyHostname = true;

		public Boolean getEnabled() {
			return this.enabled;
		}

		/**
		 * 判断 SSL 是否启用：
		 * 若未设置地址，则返回配置的 enabled 标志；
		 * 否则根据第一个地址判断 SSL 是否启用。
		 * @return 是否启用 SSL
		 * @see #setAddresses(String)
		 * @see #getEnabled()
		 */
		public boolean determineEnabled() {
			boolean defaultEnabled = Optional.ofNullable(getEnabled()).orElse(false);
			if (CollectionUtils.isEmpty(RabbitProperties.this.parsedAddresses)) {
				return defaultEnabled;
			}
			Address address = RabbitProperties.this.parsedAddresses.get(0);
			return address.determineSslEnabled(defaultEnabled);
		}

		public void setEnabled(Boolean enabled) {
			this.enabled = enabled;
		}

		public String getKeyStore() {
			return this.keyStore;
		}

		public void setKeyStore(String keyStore) {
			this.keyStore = keyStore;
		}

		public String getKeyStoreType() {
			return this.keyStoreType;
		}

		public void setKeyStoreType(String keyStoreType) {
			this.keyStoreType = keyStoreType;
		}

		public String getKeyStorePassword() {
			return this.keyStorePassword;
		}

		public void setKeyStorePassword(String keyStorePassword) {
			this.keyStorePassword = keyStorePassword;
		}

		public String getKeyStoreAlgorithm() {
			return this.keyStoreAlgorithm;
		}

		public void setKeyStoreAlgorithm(String keyStoreAlgorithm) {
			this.keyStoreAlgorithm = keyStoreAlgorithm;
		}

		public String getTrustStore() {
			return this.trustStore;
		}

		public void setTrustStore(String trustStore) {
			this.trustStore = trustStore;
		}

		public String getTrustStoreType() {
			return this.trustStoreType;
		}

		public void setTrustStoreType(String trustStoreType) {
			this.trustStoreType = trustStoreType;
		}

		public String getTrustStorePassword() {
			return this.trustStorePassword;
		}

		public void setTrustStorePassword(String trustStorePassword) {
			this.trustStorePassword = trustStorePassword;
		}

		public String getTrustStoreAlgorithm() {
			return this.trustStoreAlgorithm;
		}

		public void setTrustStoreAlgorithm(String trustStoreAlgorithm) {
			this.trustStoreAlgorithm = trustStoreAlgorithm;
		}

		public String getAlgorithm() {
			return this.algorithm;
		}

		public void setAlgorithm(String sslAlgorithm) {
			this.algorithm = sslAlgorithm;
		}

		public boolean isValidateServerCertificate() {
			return this.validateServerCertificate;
		}

		public void setValidateServerCertificate(boolean validateServerCertificate) {
			this.validateServerCertificate = validateServerCertificate;
		}

		public boolean getVerifyHostname() {
			return this.verifyHostname;
		}

		public void setVerifyHostname(boolean verifyHostname) {
			this.verifyHostname = verifyHostname;
		}

	}

	public static class Cache {

		private final Channel channel = new Channel();

		private final Connection connection = new Connection();

		public Channel getChannel() {
			return this.channel;
		}

		public Connection getConnection() {
			return this.connection;
		}

		public static class Channel {

			/**
			 * 缓存中保留的通道数量。当 "check-timeout" > 0 时，表示每个连接的最大通道数。
			 */
			private Integer size;

			/**
			 * 当缓存大小达到上限时，获取通道的等待时长。如果为 0，则总是创建新通道。
			 */
			private Duration checkoutTimeout;

			public Integer getSize() {
				return this.size;
			}

			public void setSize(Integer size) {
				this.size = size;
			}

			public Duration getCheckoutTimeout() {
				return this.checkoutTimeout;
			}

			public void setCheckoutTimeout(Duration checkoutTimeout) {
				this.checkoutTimeout = checkoutTimeout;
			}

		}

		public static class Connection {

			/**
			 * 连接工厂缓存模式。
			 */
			private CacheMode mode = CacheMode.CHANNEL;

			/**
			 * 缓存的连接数量，仅当模式为 CONNECTION 时适用。
			 */
			private Integer size;

			public CacheMode getMode() {
				return this.mode;
			}

			public void setMode(CacheMode mode) {
				this.mode = mode;
			}

			public Integer getSize() {
				return this.size;
			}

			public void setSize(Integer size) {
				this.size = size;
			}

		}

	}

	public enum ContainerType {

		/**
		 * RabbitMQ 消费者将消息分发给调用线程的容器。
		 */
		SIMPLE,

		/**
		 * 监听器直接在 RabbitMQ 消费者线程上调用的容器。
		 */
		DIRECT,

		/**
		 * 使用 RabbitMQ Stream 客户端的容器。
		 */
		STREAM

	}

	public static class Listener {

		/**
		 * 监听器容器类型。
		 */
		private ContainerType type = ContainerType.SIMPLE;

		private final SimpleContainer simple = new SimpleContainer();

		private final DirectContainer direct = new DirectContainer();

		private final StreamContainer stream = new StreamContainer();

		public ContainerType getType() {
			return this.type;
		}

		public void setType(ContainerType containerType) {
			this.type = containerType;
		}

		public SimpleContainer getSimple() {
			return this.simple;
		}

		public DirectContainer getDirect() {
			return this.direct;
		}

		public StreamContainer getStream() {
			return this.stream;
		}

	}

	public abstract static class BaseContainer {

		/**
		 * 是否在启动时自动启动容器。
		 */
		private boolean autoStartup = true;

		public boolean isAutoStartup() {
			return this.autoStartup;
		}

		public void setAutoStartup(boolean autoStartup) {
			this.autoStartup = autoStartup;
		}

	}

	public abstract static class AmqpContainer extends BaseContainer {

		/**
		 * 容器的确认模式。
		 */
		private AcknowledgeMode acknowledgeMode;

		/**
		 * 每个消费者最多允许未确认的消息数量。
		 */
		private Integer prefetch;

		/**
		 * 是否默认对被拒绝的投递重新入队。
		 */
		private Boolean defaultRequeueRejected;

		/**
		 * 空闲容器事件发布的频率。
		 */
		private Duration idleEventInterval;

		/**
		 * 容器是否应将批处理消息作为独立消息呈现，或将整个批次传递给监听器。
		 */
		private boolean deBatchingEnabled = true;

		/**
		 * 重试拦截器的可选属性。
		 */
		private final ListenerRetry retry = new ListenerRetry();

		public AcknowledgeMode getAcknowledgeMode() {
			return this.acknowledgeMode;
		}

		public void setAcknowledgeMode(AcknowledgeMode acknowledgeMode) {
			this.acknowledgeMode = acknowledgeMode;
		}

		public Integer getPrefetch() {
			return this.prefetch;
		}

		public void setPrefetch(Integer prefetch) {
			this.prefetch = prefetch;
		}

		public Boolean getDefaultRequeueRejected() {
			return this.defaultRequeueRejected;
		}

		public void setDefaultRequeueRejected(Boolean defaultRequeueRejected) {
			this.defaultRequeueRejected = defaultRequeueRejected;
		}

		public Duration getIdleEventInterval() {
			return this.idleEventInterval;
		}

		public void setIdleEventInterval(Duration idleEventInterval) {
			this.idleEventInterval = idleEventInterval;
		}

		public abstract boolean isMissingQueuesFatal();

		public boolean isDeBatchingEnabled() {
			return this.deBatchingEnabled;
		}

		public void setDeBatchingEnabled(boolean deBatchingEnabled) {
			this.deBatchingEnabled = deBatchingEnabled;
		}

		public ListenerRetry getRetry() {
			return this.retry;
		}

	}

	/**
	 * {@code SimpleMessageListenerContainer} 的配置属性。
	 */
	public static class SimpleContainer extends AmqpContainer {

		/**
		 * 监听器调用线程的最小数量。
		 */
		private Integer concurrency;

		/**
		 * 监听器调用线程的最大数量。
		 */
		private Integer maxConcurrency;

		/**
		 * 容器使用的批处理大小，以物理消息的数量表示。
		 */
		private Integer batchSize;

		/**
		 * 如果容器声明的队列在代理上不可用，是否导致失败；以及是否在运行时删除一个或多个队列时停止容器。
		 */
		private boolean missingQueuesFatal = true;

		/**
		 * 容器是否基于 'receive-timeout' 和 'batch-size' 创建消息批处理。
		 * 将 'de-batching-enabled' 强制设为 true，以将生产者创建的批次内容作为独立记录包含在批处理中。
		 */
		private boolean consumerBatchEnabled;

		public Integer getConcurrency() {
			return this.concurrency;
		}

		public void setConcurrency(Integer concurrency) {
			this.concurrency = concurrency;
		}

		public Integer getMaxConcurrency() {
			return this.maxConcurrency;
		}

		public void setMaxConcurrency(Integer maxConcurrency) {
			this.maxConcurrency = maxConcurrency;
		}

		public Integer getBatchSize() {
			return this.batchSize;
		}

		public void setBatchSize(Integer batchSize) {
			this.batchSize = batchSize;
		}

		@Override
		public boolean isMissingQueuesFatal() {
			return this.missingQueuesFatal;
		}

		public void setMissingQueuesFatal(boolean missingQueuesFatal) {
			this.missingQueuesFatal = missingQueuesFatal;
		}

		public boolean isConsumerBatchEnabled() {
			return this.consumerBatchEnabled;
		}

		public void setConsumerBatchEnabled(boolean consumerBatchEnabled) {
			this.consumerBatchEnabled = consumerBatchEnabled;
		}

	}

	/**
	 * {@code DirectMessageListenerContainer} 的配置属性。
	 */
	public static class DirectContainer extends AmqpContainer {

		/**
		 * 每个队列的消费者数量。
		 */
		private Integer consumersPerQueue;

		/**
		 * 如果容器声明的队列在代理上不可用，是否导致失败。
		 */
		private boolean missingQueuesFatal = false;

		public Integer getConsumersPerQueue() {
			return this.consumersPerQueue;
		}

		public void setConsumersPerQueue(Integer consumersPerQueue) {
			this.consumersPerQueue = consumersPerQueue;
		}

		@Override
		public boolean isMissingQueuesFatal() {
			return this.missingQueuesFatal;
		}

		public void setMissingQueuesFatal(boolean missingQueuesFatal) {
			this.missingQueuesFatal = missingQueuesFatal;
		}

	}

	public static class StreamContainer extends BaseContainer {

		/**
		 * 容器是否支持监听器消费原生流消息，而非 Spring AMQP 消息。
		 */
		private boolean nativeListener;

		public boolean isNativeListener() {
			return this.nativeListener;
		}

		public void setNativeListener(boolean nativeListener) {
			this.nativeListener = nativeListener;
		}

	}

	public static class Template {

		private final Retry retry = new Retry();

		/**
		 * 是否启用 mandatory 消息。
		 */
		private Boolean mandatory;

		/**
		 * receive() 操作的超时时间。
		 */
		private Duration receiveTimeout;

		/**
		 * sendAndReceive() 操作的超时时间。
		 */
		private Duration replyTimeout;

		/**
		 * 用于发送操作的默认交换机名称。
		 */
		private String exchange = "";

		/**
		 * 用于发送操作的默认路由键值。
		 */
		private String routingKey = "";

		/**
		 * 默认接收消息的队列名称，当未显式指定时使用。
		 */
		private String defaultReceiveQueue;

		public Retry getRetry() {
			return this.retry;
		}

		public Boolean getMandatory() {
			return this.mandatory;
		}

		public void setMandatory(Boolean mandatory) {
			this.mandatory = mandatory;
		}

		public Duration getReceiveTimeout() {
			return this.receiveTimeout;
		}

		public void setReceiveTimeout(Duration receiveTimeout) {
			this.receiveTimeout = receiveTimeout;
		}

		public Duration getReplyTimeout() {
			return this.replyTimeout;
		}

		public void setReplyTimeout(Duration replyTimeout) {
			this.replyTimeout = replyTimeout;
		}

		public String getExchange() {
			return this.exchange;
		}

		public void setExchange(String exchange) {
			this.exchange = exchange;
		}

		public String getRoutingKey() {
			return this.routingKey;
		}

		public void setRoutingKey(String routingKey) {
			this.routingKey = routingKey;
		}

		public String getDefaultReceiveQueue() {
			return this.defaultReceiveQueue;
		}

		public void setDefaultReceiveQueue(String defaultReceiveQueue) {
			this.defaultReceiveQueue = defaultReceiveQueue;
		}

	}

	public static class Retry {

		/**
		 * 是否启用发布重试。
		 */
		private boolean enabled;

		/**
		 * 传递消息的最大尝试次数。
		 */
		private int maxAttempts = 3;

		/**
		 * 第一次和第二次传递消息尝试之间的时间间隔。
		 */
		private Duration initialInterval = Duration.ofMillis(1000);

		/**
		 * 应用于前一次重试间隔的倍数。
		 */
		private double multiplier = 1.0;

		/**
		 * 尝试之间的最大时间间隔。
		 */
		private Duration maxInterval = Duration.ofMillis(10000);

		public boolean isEnabled() {
			return this.enabled;
		}

		public void setEnabled(boolean enabled) {
			this.enabled = enabled;
		}

		public int getMaxAttempts() {
			return this.maxAttempts;
		}

		public void setMaxAttempts(int maxAttempts) {
			this.maxAttempts = maxAttempts;
		}

		public Duration getInitialInterval() {
			return this.initialInterval;
		}

		public void setInitialInterval(Duration initialInterval) {
			this.initialInterval = initialInterval;
		}

		public double getMultiplier() {
			return this.multiplier;
		}

		public void setMultiplier(double multiplier) {
			this.multiplier = multiplier;
		}

		public Duration getMaxInterval() {
			return this.maxInterval;
		}

		public void setMaxInterval(Duration maxInterval) {
			this.maxInterval = maxInterval;
		}

	}

	public static class ListenerRetry extends Retry {

		/**
		 * 重试是无状态（stateless）还是有状态（stateful）。
		 */
		private boolean stateless = true;

		public boolean isStateless() {
			return this.stateless;
		}

		public void setStateless(boolean stateless) {
			this.stateless = stateless;
		}

	}

	private static final class Address {

		private static final String PREFIX_AMQP = "amqp://";

		private static final String PREFIX_AMQP_SECURE = "amqps://";

		private String host;

		private int port;

		private String username;

		private String password;

		private String virtualHost;

		private Boolean secureConnection;

		private Address(String input, boolean sslEnabled) {
			input = input.trim();
			input = trimPrefix(input);
			input = parseUsernameAndPassword(input);
			input = parseVirtualHost(input);
			parseHostAndPort(input, sslEnabled);
		}

		private String trimPrefix(String input) {
			if (input.startsWith(PREFIX_AMQP_SECURE)) {
				this.secureConnection = true;
				return input.substring(PREFIX_AMQP_SECURE.length());
			}
			if (input.startsWith(PREFIX_AMQP)) {
				this.secureConnection = false;
				return input.substring(PREFIX_AMQP.length());
			}
			return input;
		}

		private String parseUsernameAndPassword(String input) {
			if (input.contains("@")) {
				String[] split = StringUtils.split(input, "@");
				String creds = split[0];
				input = split[1];
				split = StringUtils.split(creds, ":");
				this.username = split[0];
				if (split.length > 0) {
					this.password = split[1];
				}
			}
			return input;
		}

		private String parseVirtualHost(String input) {
			int hostIndex = input.indexOf('/');
			if (hostIndex >= 0) {
				this.virtualHost = input.substring(hostIndex + 1);
				if (this.virtualHost.isEmpty()) {
					this.virtualHost = "/";
				}
				input = input.substring(0, hostIndex);
			}
			return input;
		}

		private void parseHostAndPort(String input, boolean sslEnabled) {
			int bracketIndex = input.lastIndexOf(']');
			int colonIndex = input.lastIndexOf(':');
			if (colonIndex == -1 || colonIndex < bracketIndex) {
				this.host = input;
				this.port = (determineSslEnabled(sslEnabled)) ? DEFAULT_PORT_SECURE : DEFAULT_PORT;
			}
			else {
				this.host = input.substring(0, colonIndex);
				this.port = Integer.parseInt(input.substring(colonIndex + 1));
			}
		}

		private boolean determineSslEnabled(boolean sslEnabled) {
			return (this.secureConnection != null) ? this.secureConnection : sslEnabled;
		}

	}

	public static final class Stream {

		/**
		 * 启用 Stream 插件的 RabbitMQ 实例的主机地址。
		 */
		private String host = "localhost";

		/**
		 * 启用 Stream 插件的 RabbitMQ 实例的流端口号。
		 */
		private int port = DEFAULT_STREAM_PORT;

		/**
		 * 用于认证到代理的登录用户名。未设置时使用 spring.rabbitmq.username。
		 */
		private String username;

		/**
		 * 用于认证到代理的登录密码。未设置时使用 spring.rabbitmq.password。
		 */
		private String password;

		/**
		 * 流的名称。
		 */
		private String name;

		public String getHost() {
			return this.host;
		}

		public void setHost(String host) {
			this.host = host;
		}

		public int getPort() {
			return this.port;
		}

		public void setPort(int port) {
			this.port = port;
		}

		public String getUsername() {
			return this.username;
		}

		public void setUsername(String username) {
			this.username = username;
		}

		public String getPassword() {
			return this.password;
		}

		public void setPassword(String password) {
			this.password = password;
		}

		public String getName() {
			return this.name;
		}

		public void setName(String name) {
			this.name = name;
		}

	}

}
